package com.fly.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

@RestController
public class AsyncController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    // Callable 实现多线程
    @RequestMapping("/order")
    public Callable<String> order() throws Exception {
        logger.info("主线程开始...");
        Callable<String> res = new Callable<String>() {
            @Override
            public String call() throws Exception {
                logger.info("副线程开始");
                Thread.sleep(1000);
                logger.info("副线程返回");
                return "success";
            }
        };
        return res;
    }

    @Autowired
    private FlyQueue flyQueue;
    @Autowired
    private DeferredResultHolder deferredResultHolder;

    // DeferredResult 实现多线程
    @RequestMapping("/order2")
    public DeferredResult<String> order2() throws Exception {
        logger.info("主线程开始...");
        String orderNumber = RandomStringUtils.randomNumeric(8);
        flyQueue.setPlaceOrder(orderNumber);
        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, result);
        return result;
    }
}
